package com.example.barrage.service;

import com.example.barrage.model.BarrageMessage;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

@Service
public class BarrageProducerService {

    private static final Logger logger = LoggerFactory.getLogger(BarrageProducerService.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    private ObjectMapper objectMapper = new ObjectMapper();

    private static final String TOPIC = "barrage-topic";

    /**
     * 发送弹幕消息到RocketMQ
     *
     * @param barrageMessage 弹幕消息
     */
    public void sendBarrageMessage(BarrageMessage barrageMessage) {
        try {
            logger.info("准备发送弹幕消息 - 用户ID: {}, 用户名: {}, 内容: {}", 
                barrageMessage.getUserId(), barrageMessage.getUsername(), barrageMessage.getContent());
            String jsonMessage = objectMapper.writeValueAsString(barrageMessage);
            logger.debug("序列化弹幕消息: {}", jsonMessage);
            rocketMQTemplate.send(TOPIC, MessageBuilder.withPayload(jsonMessage).build());
            logger.info("成功发送弹幕消息到RocketMQ主题: {}", TOPIC);
        } catch (Exception e) {
            logger.error("发送弹幕消息到RocketMQ失败", e);
        }
    }
}